package com.victor.service.impl;

import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.victor.dao.FreetimeDao;
import com.victor.entity.FreeTime;
import com.victor.entity.Picturebook;
import com.victor.entity.Recharge;
import com.victor.service.FreetimeService;
import com.victor.utils.DateUtils;

@Service
public class FreetimeServiceImpl implements FreetimeService {

	@Autowired
	private FreetimeDao freetimeDao;

	// 通过用户id和书id查询freetime表
	@Override
	public FreeTime getFreeByUseridAndPicid(String userid, String picid) {
		return freetimeDao.getFreeByUseridAndPicid(userid, picid);
	}

	// 将freetime信息插入数据库
	@Override
	public boolean addFreeTime(FreeTime free) {
		return freetimeDao.addFreeTime(free) > 0 ? true : false;
	}

	// 更新状态
	@Override
	public void updateState() {// 0.限时免费中,1限时免费结束,2.已购买此书)
		// 查出所有状态为0的数据
		List<FreeTime> freeTimes = freetimeDao.getFreeDoing();
		for (FreeTime freeTime : freeTimes) {
			// 获取该次结束时间
			String endtime = freeTime.getEndtime();
			Date endtimeDate = DateUtils.str2Date(endtime);
			Date now = new Date();
			if (endtimeDate.before(now)) {
				// 已经过期,修改状态
				freetimeDao.updateState(freeTime.getId());
			}
			// 未过期则无需处理
		}
	}

	// 购买回调时候的判断 传入用户id和绘本id
	@Override
	public void updateStateToReceive(String userid, String picid) {
		// 通过userid 和picid查询记录
		FreeTime freeTime = freetimeDao.getFreeByUseridAndPicid(userid, picid);
		if (freeTime != null) {// 如果不是空，则修改其状态为2
			freetimeDao.updateStateTo2(freeTime.getId());
		} else {// 如果是空，则插入此条数据 状态为2
			freeTime = new FreeTime();

			freeTime.setUserid(userid);
			freeTime.setPicid(picid);
			freeTime.setStarttime("");
			freeTime.setEndtime("");
			freeTime.setState("2");
			freetimeDao.addFreeTime(freeTime);
		}

	}

	@Override
	public void updateStateToReceiveByOrderidAndSid(String orderid) {
		// 通过orderid查询userid和系列id
		Recharge recharge = freetimeDao.getRechargeByOrderid(orderid);
//		// 拿到用户id
//		recharge.getUserid();
//		// 拿到系列id
//		recharge.getSid();

		// 通过系列id查询绘本list
		List<Picturebook> picturebooks = freetimeDao.getPicturebooksBySid(recharge.getSid());
		for (Picturebook picturebook : picturebooks) {

			FreeTime free = new FreeTime();
			free.setPicid(String.valueOf(picturebook.getPId()));
			free.setState("2");
			freetimeDao.addFreeTime(free);
		}
	}
}
